import React, { Component } from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { Link } from 'react-router'
import { Table, Spin, Form, Row, Col, Input, Button, Select, TreeSelect, DatePicker, Checkbox, message, Dropdown, Menu, Icon } from 'antd'
import _ from 'lodash'
import moment from 'moment'

import Ajax from 'lib/Ajax'
import { addConfig } from 'actions/config'
import { getNewTreeData, findRowData, getNameByCode, confirmDelete } from 'lib/fun'

const FormItem = Form.Item;
const SelectTreeNode = TreeSelect.TreeNode;
const Option = Select.Option;
const { RangePicker } = DatePicker;

class Filter extends Component {
  constructor(props) {
    super(props);
    this.state = {
      treeData: [],
      areaId: ""
    }
  }

  componentDidMount(){
    // this.loadArea();
    if(this.props.common.user&&this.props.common.user.user&&this.state.treeData.length == 0){
      this.setState({
        treeData:[{
          areaId: this.props.common.user.user.areaId,
          areaName: this.props.common.user.user.areaName,
        }]
      });
    }
  }

  componentWillReceiveProps(nextProps){
    if(!nextProps.visible){
      // this.props.form.resetFields();
    }else{
      // if(nextProps.common.user&&nextProps.common.user.user&&this.state.treeData.length == 0){
      //   this.loadArea();
      // }
    }

    if(nextProps.common.user&&nextProps.common.user.user&&this.state.treeData.length == 0){
      this.setState({
        treeData:[{
          areaId: nextProps.common.user.user.areaId,
          areaName: nextProps.common.user.user.areaName,
        }]
      });
    }
  }

  loadArea = (treeNode)=>{
    console.log('load area');
    var self = this;
    var selected = findRowData(self.state.treeData, treeNode?treeNode.props.eventKey:0, 'areaId');
    return new Promise((resolve) => {
      if(selected&&selected.children){
        resolve();
      }else{
        Ajax({
          url: '/area/list',
          data: {
            areaParentId: treeNode?treeNode.props.eventKey:0,
            perPage: 100
          },
          success: function(data){
            var treeData = self.state.treeData;
            if(treeNode&&self.state.treeData.length > 0){
              treeData = getNewTreeData(treeData, treeNode.props.eventKey, data.list, 'areaId');
            }else{
              treeData = data.list;
            }
            self.setState({
              treeData
            });
            resolve();
          },
          error: function(error){
            message.error(error);
          }
        });
      }
    });
  }

  handleSearch = (e) => {
    var self = this;
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if(err == null){
        self.props.handleFilter(values);
        self.setState({
          areaId: values.areaId
        });
      }
    });
  }

  handleAll = (e) => {
    var self = this;
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if(err == null){
        self.props.handleFilter(values, true);
      }
    });
  }

  areaChange = (value)=>{
    var self = this;
    this.props.form.validateFields((err, values) => {
      self.props.areaChange(Object.assign(values, {
        areaId: value
      }));
      self.setState({
        areaId: value
      });
    });
  }

  handleReset = () => {
    this.props.form.resetFields();
  }

  getButtonText = ()=>{
    const { type } = this.props;
    var back = '导出当前所有用户'
    if(type == 2){
      back = "选中当前所有用户"
    }else if(type == 3){
      back = "新增当前所有用户"
    }
    return back
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: { span: 10 },
      wrapperCol: { span: 14 },
    };
    const formItemLayout2 = {
      labelCol: { span: 16 },
      wrapperCol: { span: 8 },
    };

    const loop = data => data.map((item) => {
      if (item.children&&item.children.length > 0) {
        return <SelectTreeNode title={item.areaName} key={item.areaId+""} value={item.areaId + ""}>{loop(item.children)}</SelectTreeNode>;
      }
      console.log('isLeaf',item.children&&item.children.length == 0 );
      return <SelectTreeNode title={item.areaName} key={item.areaId+""} value={item.areaId + ""} isLeaf={item.children&&item.children.length == 0}/>;
    });
    const treeNodes = loop(this.state.treeData);
    
    return (<div className="ant-advanced-search-form">
          <Row>
            <Col span={8}>
              <FormItem {...formItemLayout} label="区划名称">
                {getFieldDecorator("areaId")(
                    <TreeSelect
                      dropdownMatchSelectWidth={false}
                      size="default"
                      loadData={ this.loadArea }
                      onChange={this.areaChange}
                    >
                      { treeNodes }
                    </TreeSelect>
                )}
              </FormItem>
            </Col>
            <Col span={6}>
              <FormItem {...formItemLayout} label="用户姓名">
                {getFieldDecorator("name")(
                  <Input />
                )}
              </FormItem>
            </Col>
            <Col span={6}>
              <FormItem {...formItemLayout} label="身份证">
                {getFieldDecorator("identNumber")(
                  <Input />
                )}
              </FormItem>
            </Col>
            <Col span={4}>
              <FormItem {...formItemLayout2} label="是否户主">
                {getFieldDecorator("master", {
                  valuePropName: 'checked'
                })(
                  <Checkbox />
                )}
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span={24}>
              <div className="btn-box" style={{ textAlign: 'center' }}>
                <Button type="primary" onClick={this.handleSearch}>查询</Button>
                <Button style={{ marginLeft: 8 }} onClick={this.handleReset}>
                  重置
                </Button>
                <span style={{float:'right'}}>
                  <Button type="primary" disabled={ !(!!this.state.areaId&&this.props.num) }  onClick={this.handleAll}>{this.getButtonText()}</Button>
                </span>
              </div>
            </Col>
          </Row>
        </div>);
  }
}
function mapStateToProps(state) {
  return {
    config: state.config,
    common: state.common
  }
}

module.exports = connect(mapStateToProps)(Form.create()(Filter))